<template>
  <div class="app-container">

   <div class="filter-container">

      <el-date-picker
      v-model="value2"
      type="daterange"
      align="right"
      unlink-panels
      range-separator="至"
      start-placeholder="开始日期"
      end-placeholder="结束日期"
      :picker-options="pickerOptions" @change='changeData(value2)'>
    </el-date-picker>

     <el-input
          placeholder="输入手机号查询"
          v-model="input_conten"
          clearable class='inp_search'>
      </el-input>

      <el-select v-model="selectState"  placeholder="状态"  clearable class='inp_search' >
          <el-option
          v-for="item in optionState"
          :key="item.value"
          :label="item.label"
          :value="item.value">
          </el-option>
      </el-select>
      
      <el-button  class="filter-item" type="primary" icon="el-icon-search"  @click="searchList">
        搜索
      </el-button>
      <el-button  class="filter-item" type="primary" icon="el-icon-refresh"  @click="resList">
        重置
      </el-button>
    </div>
     
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column label="单据ID" min-width="150" align="center">
        <template slot-scope="scope">
            <span v-if="scope.row.billId === null">--</span>
            <span v-else> {{scope.row.billId}} </span>
        </template>
      </el-table-column>

      <el-table-column label="单据号" min-width="150" align="center">
        <template slot-scope="scope">
            <span v-if="scope.row.pillId === null">--</span>
            <span v-else> {{scope.row.pillId}} </span>
        </template>
      </el-table-column>

      <el-table-column label="时间" min-width="200" align="center">
        <template slot-scope="scope">
            <span v-if="scope.row.time === null">--</span>
            <span v-else> {{scope.row.time}} </span>
        </template>
      </el-table-column>

      <el-table-column label="用户手机号" min-width="150" align="center">
        <template slot-scope="scope">
            <span v-if="scope.row.userPhone === null">--</span>
            <span v-else> {{scope.row.userPhone}} </span>
        </template>
      </el-table-column>

      <el-table-column label="员工单据"  min-width="150" align="center">
        <template slot-scope="scope">
           <span v-if="scope.row.staffImg === ''">--</span>
            <viewer v-else>
              <img :src="scope.row.staffImg " class='carImgs'>
            </viewer>
        </template>
      </el-table-column>

     <el-table-column label="仓管单据"  min-width="150" align="center">
        <template scope="scope">
            <span v-if="scope.row.adminImg === ''">--</span>
            <viewer v-else>
              <img :src="scope.row.adminImg " class='carImgs'>
            </viewer>
        </template>
      </el-table-column>

       <el-table-column label="状态"  min-width="150" align="center">
        <template scope="scope">
            <span v-if="scope.row.state === null">--</span>
            <span v-else-if="scope.row.state== 1">已录入</span>
            <span v-else>未录入</span>
        </template>
      </el-table-column>
     
      <el-table-column v-if="role== '4'"  align="center" prop="created_at" label="操作"  min-width="150" fixed='right'>
        <template scope="scope">
           <el-button type="primary" size="mini" @click="handleEdit(scope.$index, scope.row,'ruleForm')">确认</el-button>
           <el-button type="success" size="mini"  @click="addList(scope.$index, scope.row)">添加</el-button>
        </template>
      </el-table-column>

    </el-table>
   <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"  @pagination="fetchData"/>
  
   <div class='formPosition' v-if='dialogFormVisible'>
   <div class='titleForm'>
          <div class='left_titleForm'>{{titleName}}</div>
          <span class="icon iconfont right_titleForm" @click="dialogFormVisible = false">&#xe72d;</span>
   </div>
   <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm " :visible.sync="dialogFormVisible">
         
         <!-- 修改 -->
        <div v-if=" titleName== '修改'" >
          <el-form-item  label="单据ID" >
          <el-input v-model="ruleForm.billId" readonly></el-input>
          </el-form-item>

           <el-form-item  label="单据号" >
          <el-input v-model="ruleForm.pillId" readonly></el-input>
          </el-form-item>

          <el-form-item  label="时间" >
          <el-input v-model="ruleForm.time" readonly></el-input>
          </el-form-item>

          <el-form-item  label="用户手机号" >
          <el-input v-model="ruleForm.userPhone" readonly></el-input>
          </el-form-item>

          <el-form-item  label="员工单据" >
             <viewer>
               <img class='carImgs1' :src='ruleForm.staffImg' />
            </viewer>
          </el-form-item>

          <el-form-item  label="仓管单据" >
             <viewer>
               <img class='carImgs1' :src='ruleForm.adminImg'/>
            </viewer>
          </el-form-item>

          <el-form-item  label="状态" >
              <el-select v-model="addSelectState"  placeholder="请选择" class='select_roles' @change="changeState(addSelectState)">
                      <el-option
                      v-for="item in optionState"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">  
                      </el-option>
                </el-select>
          </el-form-item>
        </div>
        
        <!-- 添加 -->
        <div v-else>
           <el-row :gutter="20">
                <el-col :span="12">
                      <el-form-item  label="员工单据" >
                        <viewer>
                          <img class='carImgs1' :src='this.staffImg'/>
                        </viewer>
                      </el-form-item>
                </el-col>

                <el-col :span="12">
                      <el-form-item  label="仓库单据" >
                        <viewer>
                          <img class='carImgs1' :src='this.adminImg'/>
                        </viewer>
                      </el-form-item>
                </el-col>
           </el-row>

           <el-row :gutter="20">
                <el-col :span="12">
                      <el-form-item label="时间" >
                          <el-date-picker 
                                v-model="select_time"
                                type="date"
                                placeholder="选择日期" class='select_roles'>
                          </el-date-picker>
                      </el-form-item>
                </el-col>

                <el-col :span="12">
                       <el-form-item label="员工手机号" prop="AdduserPhone">
                          <el-input v-model="ruleForm.AdduserPhone"></el-input>
                      </el-form-item>
                </el-col>
           </el-row>
            
           <el-row :gutter="20">
                <el-col :span="12">
                      <el-form-item label="工具名称" >
                          <el-select  v-model='selestTool'  placeholder="请选择" class='select_roles' @change="changTool(selestTool)">
                                <el-option
                                  v-for="item in optionsTool"
                                  :key="item.toolId"
                                  :label="item.toolName"
                                  :value="item.toolId">
                                </el-option>
                          </el-select>
                      </el-form-item>
                </el-col>

                <el-col :span="12">
                       <el-form-item  label="工具ID" >
                            <el-input v-model="selestTool" readonly></el-input>
                        </el-form-item>
                </el-col>
           </el-row>

           <el-row :gutter="20">
                <el-col :span="12">
                       <el-form-item label="数量" prop="quantity">
                          <el-input v-model.number="ruleForm.quantity" type="number" :min="0"></el-input>
                      </el-form-item>
                </el-col>

                <el-col :span="12">
                       <el-form-item label="取用/归还" >
                          <el-select  v-model='selestStatue'  placeholder="请选择" class='select_roles' @change="changStatue(selestStatue)">
                                <el-option
                                  v-for="item in optionsStatue"
                                  :key="item.value"
                                  :label="item.label"
                                  :value="item.value">
                                </el-option>
                          </el-select>
                      </el-form-item>
                </el-col>
           </el-row>

           <el-row v-if="titleName == '添加'"  :gutter="20">
                <el-col :span="12">
                       <el-form-item label="单据号" prop="pillId">
                          <el-input v-model="ruleForm.pillId" readonly></el-input>
                      </el-form-item>
                </el-col>
                
           </el-row>
        </div>

          <el-form-item>
            <el-row v-if="titleName == '添加'"  :gutter="20">
                <el-col :span="6">
                      <el-button type="primary" @click="submitForm('ruleForm')" >确认</el-button>
                      <el-button @click="dialogFormVisible = false">取消</el-button>
                </el-col>
                <el-col :span="12">
                       <span>(当前新增第{{stockRecodeNum}}行)</span>
                </el-col>
                
           </el-row>
          </el-form-item>

          
     </el-form>
    </div>
   


  </div>
  
</template>

<script>
import { getBillManage ,modifyBillManage ,searchByPillId ,getStockRecodeNum} from '@/api/billManages'
import { getStockList , searchByPhone ,searchByStockName ,modifyStock ,addStock ,delStockList ,getTools} from '@/api/stockRecode'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination'
export default {
  components: { Pagination },
  data() {
    return {
      stockRecodeNum:0,
      role:'',
      input_conten:'',
      select_time:'',
      list: null,
      listLoading: true,
      pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
       }, 
      value2: '',
      total:0,
      titleName:'',
      listLoading: true,
      adminImg:'',
      staffImg:'',
      listQuery:{
          page: 1,
          limit: 10,
      },
      selectRoles:'',
      optionsRoles:[],
      optionState:[{
          value: 1,
          label: '已录入'
        }, {
          value: 0,
          label: '未录入'
        }],
      selectState:'',
      NEWDATASTAR:'',
      NEWDATAEND:'',
      dialogFormVisible:false,
      addSelectState:'',
      addoptionsState:[],
      optionsTool:[],
      optionsToolText:'',
      selestTool:'',
      ruleForm:{
            billId:'',
            time:'',
            userPhone:'',
            state:'',
            recordId: '',
            toolId:'',
            toolName:'',
            AdduserPhone:'',
            type:'', 
            quantity:'',
            pillId:'',
      },
      cleanForm:{
          billId:'',
          time:'',
          userPhone:'',
          state:'',
          recordId: '',
          toolId:'',
          toolName:'',
          AdduserPhone:'',
          type:'', 
          quantity:'',
          pillId:'',
      },
       rules: {
            toolName: [
            { required: true, message: '请输入工具名称', trigger: 'blur' },
          ],
          AdduserPhone: [
            { required: true, message: '请输入员工手机号', trigger: 'blur' },
            {
            pattern: /^1[0-9]{10}$/,
            message: '手机号格式不对',
            trigger: 'blur'
          }
          ],
          type: [
            { type: 'array', required: true, message: '请选择取用/归还', trigger: 'change' }
          ],
          quantity: [
             {type: 'number',required: true, message: '请输入正确格式的数量', trigger: 'change' }
          ]
       },
        optionsStatue:[{
          value: '1',
          label: '取用'
      },{
          value: '0',
          label: '归还'
      }],
      selestStatue:'',
    }
  },
  created() {
     this.selectState = this.optionState[0].lable;
     const userInfo  = localStorage.getItem('userInfo');
     this.role = JSON.parse(userInfo).role;
     this.fetchData()
     this.getToolData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      const beginData = '';
      const endData = '';
      if(this.selectState == undefined ){
          this.selectState= ""
      }
      const paramsData = {
        curPage:this.listQuery.page,
        pageSize:this.listQuery.limit,
        startDate:this.NEWDATASTAR,
        endDate:this.NEWDATAEND,
        userPhone:this.input_conten,
        state:this.selectState
        }
      getBillManage(paramsData).then(res => {
        this.total = res.data.countNum;
        this.list =  res.data.obj;
        this.listLoading = false
      })
    },
    resList(){
          this.selectState = this.optionState[0].lable;
          const userInfo  = localStorage.getItem('userInfo');
          this.role = JSON.parse(userInfo).role;
          this.fetchData()
          this.getToolData()
      },
    searchList(){//搜索
        if(this.value2){
            this.NEWDATASTAR = this.transformDate(this.value2[0])
            this.NEWDATAEND = this.transformDate(this.value2[1])
        }
        this.fetchData();
    },
    transformDate(d){
       const newData = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();   
       return newData
    },
    changeData(data){
       if((data == undefined)||(data == null)){
             this.NEWDATASTAR = '';
             this.NEWDATAEND = '';
        }
    },
    changeState(data){
       this.addSelectState = data
    },
    handleEdit(index, row ,formName) {//修改
          // this.titleName = '修改'
          // this.dialogFormVisible = true;
          var obj = {};
          obj = this.optionState.find(item =>{
              return item.value === row.state 
          });
          this.addSelectState = obj.label
          this.ruleForm = Object.assign({}, row);
          this.modifyBill(formName)
      },
    getToolData(){
     const paramsData = {}
        getTools(paramsData).then(res => {
        this.optionsTool = res.data;
      })
   },
    addList(index, row ){
        this.dialogFormVisible = true;   
        this.ruleForm = this.cleanForm;
        this.staffImg = row.staffImg;
        this.adminImg = row.adminImg;
        this.ruleForm.pillId = row.pillId;
        this.selestStatue = ''; 
        this.select_time = ''; 
        this.selestTool = '';
        this.optionsToolText = '';
        this.titleName = '添加'

         const paramsData = {pillId:row.pillId}
        getStockRecodeNum(paramsData).then(res => {
          const datas = res.data;
          this.stockRecodeNum = this.stockRecodeNum + Number(datas) + 1;
      })
    },
    changTool(data){
             this.selestTool = data;
              var obj1 = {};
              obj1 = this.optionsTool.find(item =>{
                  return item.toolId === this.selestTool
              });
              this.optionsToolText = obj1.toolName;
              this.ruleForm.toolName = obj1.toolName;
      },
    changStatue(data){
           this.selestStatue = data;
      },
    submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.listLoading = true
            if(this.titleName=='修改'){
                this.modifyBill(formName)
            }else{
                this.addBill(formName)
            }
          } else {
             this.$notify({
                    message: '提交失败',
                    type: 'error',
                    duration: 2000
                })
            return false;
          }
        });
      },
      modifyBill(formName){
          const paramsData ={
                      billId:this.ruleForm.billId,
                      state:1
            }
             modifyBillManage(paramsData).then(res => {
                    if(res.code==200){
                          this.$notify({
                              message: '修改成功',
                              type: 'success',
                              duration: 2000
                              })    
                    }else{
                        this.$notify({
                              message: '修改失败',
                              type: 'error',
                              duration: 2000
                       })
                       return false;
                    }
                    //this.resetForm(formName)
                    this.fetchData()
                    this.listLoading = false
               })
      },
      addBill(formName){
            const paramsData = {
                  toolId:this.selestTool,
                  toolName:this.optionsToolText,
                  userPhone:this.ruleForm.AdduserPhone,
                  type: this.selestStatue,
                  quantity:this.ruleForm.quantity,
                  staffImg:this.staffImg,
                  adminImg:this.adminImg,
                  pillId:this.ruleForm.pillId
                  }
              addStock(paramsData).then(res => {
                if(res.code == '200'){
                        this.$notify({
                        message: '添加库存记录成功',
                        type: 'success',
                        duration: 2000
                    })
                  }else{
                    this.$notify({
                        message: '添加库存记录失败',
                        type: 'error',
                        duration: 2000   
                    })
                    return false;
                  }
                    this.resetForm(formName)
                    this.fetchData()
                    this.listLoading = false
            })

      },
      resetForm(formName) {
          this.ruleForm = this.cleanForm;
          this.$refs.ruleForm.resetFields();
          this.dialogFormVisible = false;  
      },
  }
  
}
</script>
<style lang="scss">
 .filter-container{
   margin-bottom:20px;
 }
 .el-date-range-picker{
   margin-left:220px;
 }
 .inp_search{
   width:20%;
   margin-right:1%;        
 }
 .formPosition{
    width:70%;
    height:auto;
    background:#fff;
    position:absolute;
    left:15%;
    top:5%;
    z-index:999;
    padding:30px;
    box-shadow: 0px 0px 5px 5px #eee;
    border-radius: 5px;
 }
 .demo-ruleForm{
      width:95%;  
 }
 .titleForm{
     width:100%;
     height:30px;
     line-height:30px;
     margin-bottom:20px;
     font-size:1.1em;
     font-weight: 500;
 }
 .left_titleForm{
    float:left;
 }
 .right_titleForm{
    display:block;
    float:right;
 }
 .select_roles{
    width:100%;
 }
 .carImgs{
   width:45px;
   height:45px;
   border-radius:5px;
   margin:0 3px;
 }
 .carImgs1{
   width:60px;
   height:60px;
   border-radius:5px;
   margin:0 3px;
   border:solid 1px #efefef;
 }
</style>
